<?php

declare(strict_types=1);

namespace App\Listener;

use App\Event\AppException;
use App\Utils\NativeLog;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * 异常事件监听器
 * Class AppExceptionListener
 * @package App\Listener
 * @Listener()
 */
class AppExceptionListener implements ListenerInterface
{

    /**
     * @Inject()
     * @var RequestInterface
     */
    private $request;


    /**
     * @Inject()
     * @var NativeLog
     */
    private $nativeLog;

    /**
     * @inheritDoc
     */
    public function listen(): array
    {
        // TODO: Implement listen() method.
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            AppException::class,
        ];
    }

    /**
     * @param object $throwable
     */
    public function process(object $throwable)
    {
        $throwable = $throwable->throwable;
        $request = $this->request;
        $AppExceptionLog['method'] = $request->getMethod();
        $AppExceptionLog['path'] = $request->url();
        $AppExceptionLog['params'] = $request->all();
        $AppExceptionLog['file'] = $throwable->getFile();
        $AppExceptionLog['line'] = $throwable->getLine();
        $AppExceptionLog['message'] = $throwable->getMessage();
        $this->nativeLog->error(json_encode($AppExceptionLog));
    }
}
